<template>
    <div class="main">
        <van-search placeholder="请输入搜索关键词" v-model="q" @search="onSearch"/>
        <template v-if="list.length > 0">
            <van-list v-model="loading"
                      :finished="finished"
                      :error.sync="error"
                      finished-text="我是有底线的!"
                      error-text="请求失败，点击重新加载"
                      @load="onLoad">
                <tk-goods v-for="item in list" :key="item.id" :data="item"></tk-goods>
            </van-list>
        </template>
        <div class="loading" v-if="loading && page === 1">
            <van-loading/>
        </div>
    </div>
</template>

<script>
    import {Search, List, Loading} from 'vant';
    import Goods from '../components/Goods.vue';

    export default {
        data() {
            return {
                q: this.$route.query.q || "",
                page: 1,
                rows: 20,
                list: [],
                finished: false,
                loading: false,
                error: false
            }
        },
        components: {
            [Search.name]: Search,
            [List.name]: List,
            [Goods.name]: Goods,
            [Loading.name]: Loading
        },
        methods: {
            onSearch() {
                this.list = [];
                this.request(this.$store.api.search, {
                    q: this.q,
                    page: 1,
                    rows: this.rows
                });
            },
            onLoad() {
                this.request(this.$store.api.search, {
                    q: this.q,
                    page: ++this.page,
                    rows: this.rows
                });
            },
            async request(url, params) {
                this.loading = true;
                try {
                    const result = await this.$http.getStore(url, params);
                    this.list.push(...result['data']);
                } catch (e) {
                    this.error = true;
                }
                this.loading = false;
            }
        },
        watch: {
            page() {
                if (this.page > 20) this.finished = true;
            }
        },
        mounted() {
            if (this.$route.query.q) {
                this.onSearch()
            }
        }
    }
</script>
<style scoped>
    .main {
        padding-top: 55px;
    }
    
    .van-list {
        margin: 10px;
    }
    
    .van-search {
        position: fixed;
        top: 45px;
        left: 0;
        width: 100%;
    }
    
    .loading {
        margin-top: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>
